# @Time : 2024/10/26 18:33
# @Author : Fioman 
# @Phone : 13149920693
"""
根据现有的数据,通过一个大括号 和 key表达式:value表达式 for item in iterable if condition的方式快捷方便
的生成一个字典的方式.
"""
# region 1. 创建元素为键,平方为值的字典,1-10
dt = {x: x ** 2 for x in range(1, 11)}
print(dt)
# endregion

# region 2. 添加过滤条件,只保留奇数
dt = {x: x ** 2 for x in range(1, 11) if x % 2 != 0}
print(dt)
# endregion

# region 3. 将现有字典的键和值进行互换
dt = {"a": 1, "b": 2, "c": 3, "d": 4}
dtNew = {value: key for key, value in dt.items()}
print(dtNew)
# endregion

# region 4. 将字符串列表转换为带有索引的字典
strList = ["Fioman", "Python", "Cpp", "Java", "Javascript"]
dt = {index: strList[index] for index in range(len(strList))}
print(dt)
# endregion

# region 5. 基于多条件生成字典,注意之类if else,在前面而不是在后面,这里的的多条件仅仅是指num:后面的值
dt = {num: "奇数" if num % 2 != 0 else "偶数" for num in range(20)}
print(dt)
# endregion

# region 6. 从两个可迭代序列配合zip生成字典
iter1 = ["name", "age", "score"]
iter2 = ("Fioman", 18, 100)
dt = {key: value for key, value in zip(iter1, iter2)}
print(dt)
# endregion

# region 7. 从已有的字典筛选固定条件的键值对
originalDict = {"a": 5, "b": 12, "c": 18, "d": 20, "e": 25}
dt = {key: value for key, value in originalDict.items() if value % 5 == 0}
print(dt)
# endregion

# region 8. 嵌套字典推导式
matrix = {i: {j: i * j for j in range(1, 4)} for i in range(1, 4)}
print(matrix)
# endregion
